<template>
  <Layout navColor="#fff">
    <u-toast ref="uToast"></u-toast>
    <!-- 查验 -->
    <scan v-if="scanShow" ref="scanRef" mode="scanCodde" :configure="configure" @check="handleScanChange" @close="handleScanClose" />

    <!-- 相机模式 -->
    <u-popup mode="center" :show="modeShow" :safeAreaInsetBottom="false" @close="handleModeClose">
      <view class="markType">
        <view v-for="value in markTypeList" :key="value" class="markType-item" @click="handleMarkTypeChange(value)">
          <text>{{ value }}</text>
        </view>
      </view>
    </u-popup>
  </Layout>
</template>

<script>
import scan from "@/components/scan/scan"

import {getNowDate, formatQuery} from "@/utils/index.js"
import {getConfigure} from "@/api/common.js"
import {takeQrCodeCheck} from "@/api/scan.js"

const {miniProgram} = wx.getAccountInfoSync()
const deviceInfo = wx.getDeviceInfo()

// 定位错误次数
let scanLocateErrCount = 0
// 偏振错误次数
let scanPolarizationErrCount = 0

export default {
  name: "Product",
  components: {
    scan
  },
  computed: {
    isLogin() {
      return this.$store.getters.isLogin
    },
    info() {
      return this.$store.state.user.info
    }
  },
  data() {
    return {
      modeShow: true, //相机模式显示
      scanShow: true, //扫描显示
      crop: false, //是否参见
      dialog: {
        show: false
      },
      errorCheckCount: 0,
      //相机模式
      markTypeList: ["Origin", "Without", "Copy", "A4"],
      markType: "Origin",
      // 参数配置
      configure: {
        iosThreshold: {},
        darkThreshold: {},
        lightThreshold: {}
      }
    }
  },
  onShow() {
    uni.showLoading({title: "相机加载中..."})
    this.$refs.scanRef && this.$refs.scanRef.restore()
  },
  onHide() {
    this.$refs.scanRef && this.$refs.scanRef.stop()
  },
  mounted() {
    uni.hideLoading()
  },
  methods: {
    // 获取参数配置
    getScanConfigure() {
      getConfigure().then(res => {
        this.configure.iosThreshold = res.iosThreshold
        this.configure.darkThreshold = res.darkThreshold
        this.configure.lightThreshold = res.lightThreshold
      })
    },
    // 扫描结果判断
    async handleScanChange(path) {
      try {
        console.log("Scan Check")

        const data = await takeQrCodeCheck(path, {
          body: JSON.stringify({
            goodsClass: this.markType,
            brandName: `${deviceInfo.brand}${deviceInfo.model}`
          })
        })

        switch (data.code) {
          case 1000: //识别成功
            this.showToast("识别成功！")
            scanLocateErrCount = 0
            scanPolarizationErrCount = 0

            this.handleToResult({type: "success", ...data.goodsBrand})
            break
          case 1001: //继续识别
            scanLocateErrCount++
            scanPolarizationErrCount = 0

            if (scanLocateErrCount == 3) {
              scanLocateErrCount = 0
              this.showToast("识别错误！")

              this.handleToResult({type: "error"})
            } else {
              this.$refs.scanRef.showTips("请对准防伪标识码！")
            }
            break
          case 1002: //识别失败
            scanLocateErrCount = 0
            scanPolarizationErrCount++
            if (scanPolarizationErrCount == 2) {
              this.$refs.scanRef && this.$refs.scanRef.restore()
              this.showToast("识别错误！")
              scanPolarizationErrCount = 0

              this.handleToResult({type: "error"})
            } else {
              this.$refs.scanRef.showTips("请对准防伪标识码！")
            }
            break
          case 1010: //采集次数
            alert("该类别已采集到一万张！")
            scanLocateErrCount = 0
            scanPolarizationErrCount = 0
            break
          default:
            scanLocateErrCount = 0
            scanPolarizationErrCount = 0
        }
      } catch (error) {
        console.log("scan check error: ", error)
      } finally {
        // 恢复扫描
        this.$refs.scanRef && this.$refs.scanRef.restore()
      }
    },
    // 跳转结果页
    handleToResult(product = {}) {
      uni.navigateTo({
        url: "/pages/result/index" + formatQuery(product)
      })
    },
    // 扫描关闭
    handleScanClose() {
      uni.navigateBack()
    },
    // 相机模式关闭
    handleModeClose() {
      this.modeShow = false
    },
    // 相机模式选择
    handleMarkTypeChange(type) {
      this.modeShow = false
      this.markType = type

      this.$refs.scanRef && this.$refs.scanRef.restore()
    },
    // 显示Toast提示
    showToast(txt) {
      this.$refs.uToast &&
        this.$refs.uToast.show({
          message: txt,
          position: "bottom"
        })
    }
  }
}
</script>

<style lang="scss" scoped>
// 相机模式
.markType {
  display: flex;
  flex-direction: column;
  row-gap: 20rpx;
  font-size: 24rpx;
  border-radius: 42rpx;
  .markType-item {
    padding: 40rpx 200rpx;
    text-align: center;
    &:hover {
      background-color: #f5f5f5;
    }
  }
}
</style>
